package com.tanhua.sso.controller;

import com.tanhua.sso.entity.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description AUTO
 * @ClassName UserController
 * @Author ZhengXinjie
 * @date 2021.02.06 14:23
 */
@RestController
@RequestMapping("user")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param){
        try {
            // 获取前端发送过来的信息
            String phone = param.get("phone");
            String verificationCode = param.get("verificationCode");
            // 调用业务层登录方法
            String data = userService.login(phone, verificationCode);
            // 如果为空则登录失败
            if(StringUtils.isNotEmpty(data)){
                // 登录成功
                // 获取token和isNew
                String[] split = StringUtils.split(data, "|");
                Map<String, Object> result = new HashMap<>();
                result.put("token", split[0]);
                result.put("isNew", Boolean.valueOf(split[1]));

                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 登录失败, 返回错误结果对象
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token){
        return userService.queryUserByToken(token);
    }
}

